package org.example.demo.common.serializer.impl;

import org.example.demo.common.serializer.Serializer;
import org.example.demo.common.serializer.SerializerFactory;
import org.example.demo.common.serializer.SerializerVariety;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class SerializerFactoryImpl implements SerializerFactory {
    private static final Logger LOGGER = LoggerFactory.getLogger(SerializerFactoryImpl.class);

    private static final Map<SerializerVariety, Class<? extends Serializer>> MAP = new HashMap<>();

    static {
        MAP.put(SerializerVariety.JSON, JSONSerializer.class);
        MAP.put(SerializerVariety.ANOTHER, AnotherSerializer.class);
    }

    private SerializerFactoryImpl() {}

    private static class SerializerFactoryHolder {
        private static final SerializerFactoryImpl INSTANCE = new SerializerFactoryImpl();
    }

    public static SerializerFactoryImpl getInstance() {
        return SerializerFactoryHolder.INSTANCE;
    }

    @Override
    public Serializer create(SerializerVariety type, Class<?> serializeClass) {
        try {
            Class<? extends Serializer> clazz = MAP.get(type);
            Constructor<? extends Serializer> constructor = clazz.getConstructor(Class.class);
            return  constructor.newInstance(serializeClass);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            LOGGER.error(e.getMessage());
        }
        return null;
    }
}
